<template>
  <div class="page-common-layout custom-tablePage-container">
    <div class="screen-conditions-container">
      <ScreenConditions :isDataType="false">
        <template slot="conditions">
          <a-select
            showSearch
            :filter-option="filterOption"
            v-model="condition.orgCode"
            :loading="blockLoading"
            placeholder="请选择标段"
            @change="search($event)"
            class="project-select"
          >
            <a-select-option
              :value="item.orgCode"
              v-for="item in blockSoucre"
              :key="item.uuid"
            >
              {{ item.orgName }}
            </a-select-option>
          </a-select>

          <a-input
            placeholder="请输入姓名"
            v-model.trim="condition.userName"
            allowClear
          >
          </a-input
        ></template>
        <template slot="operate">
          <a-button class="cu-btn-primary" icon="search" @click="search()">
            查询
          </a-button>
          <a-button class="cu-btn-filter" icon="reload" @click="reset()">
            重置
          </a-button>
        </template>
      </ScreenConditions>
    </div>
    <div class="table-body-container">
      <div class="table-operate">
        <a-button
          @click="handleAdd()"
          class="cu-btn-primary margin-bottom-xs"
          icon="plus"
          v-action:ryda_add
        >
          新增
        </a-button>
        <a-button
          @click="exportExcel()"
          class="cu-btn-primary margin-bottom-xs"
          icon="export"
          :loading="exportLoading"
        >
          导出
        </a-button>
        <a-button
          @click="downloadTemplate()"
          class="cu-btn-primary margin-bottom-xs"
          icon="download"
          v-if="condition.orgCode"
        >
          下载模版
        </a-button>
        <a-button
          v-if="condition.orgCode"
          @click="importTemplate()"
          class="cu-btn-primary margin-bottom-xs"
          icon="upload"
          :loading="importLoading"
        >
          模版导入
        </a-button>
        <input
          accept=".xls,.xlsx"
          @change="importExcel"
          type="file"
          ref="upload"
          id="upload"
          style="display: none"
        />
      </div>
      <div class="table-main">
        <vxe-table
          ref="xTable"
          height="99%"
          align="center"
          show-overflow
          show-header-overflow
          border="inner"
          :data="tableData"
          :column-config="{ resizable: true }"
          size="small"
          :loading="loading"
        >
          <vxe-column type="seq" width="80" title="序号"></vxe-column>
          <vxe-column field="orgName" title="所属单位" width="300">
          </vxe-column>
          <vxe-column field="sectype" title="角色"> </vxe-column>
          <vxe-column field="userName" title="姓名"> </vxe-column>
          <vxe-column field="sexName" title="性别"> </vxe-column>
          <vxe-column field="phoneNum" title="手机号"> </vxe-column>
          <vxe-column field="birthDate" title="出生日期"> </vxe-column>
          <vxe-column field="userTypeName" title="人员种类"> </vxe-column>
          <vxe-column field="postName" title="岗位名称"> </vxe-column>
          <vxe-column title="附件" width="100">
            <template #default="{ row ,  }">
              <!--  -->
              <div class="files-icon">
                <a-tooltip placement="top">
                  <template slot="title"> 预览 </template>
                  <a-icon
                    type="eye"
                    class="preview-btn"
                    @click="handelFileModal(row)"
                    :class="[analysisPath(row).length == 0 && 'disabled']"
                  />
                </a-tooltip>
              </div>
            </template>
          </vxe-column>
          <vxe-column
            field="operate"
            width="120"
            title="操作"
            fixed="right"
            align="left"
          >
            <template #default="{ row }">
              <div class="text-button-group">
                <a-tooltip>
                  <template slot="title">
                    查看
                  </template>
                  <a-icon type="file-search" @click="gotoDetail(row)" />
                </a-tooltip>
                <a-tooltip placement="top" v-action:ryda_edit>
                  <template slot="title">
                    编辑
                  </template>
                  <a-icon type="edit" class="edit-btn" @click="editor(row)" />
                </a-tooltip>
                <a-tooltip placement="top" v-action:ryda_delete>
                  <template slot="title">
                    删除
                  </template>
                  <a-icon
                    type="delete"
                    class="delete-btn"
                    @click="handleDelClick(row)"
                  />
                </a-tooltip>
              </div>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div class="table-pager">
        <vxe-pager
          size="small"
          background
          :current-page.sync="pager.page"
          :page-size.sync="pager.pageSize"
          :total="pager.total"
          :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes']"
          :page-sizes="[20, 50, 100, 500]"
          @page-change="paginationChange"
        >
          <template #left>
            <div class="vxe-pager-left-tip-container">
              共<span>{{ pager.total }}</span
              >条
            </div>
          </template>
        </vxe-pager>
      </div>
    </div>
    <!-- 编辑弹窗-->
    <edit-form
      ref="createModal"
      :visible="visible"
      :loading="confirmLoading"
      :url="url"
      requestMethod="post"
      :tableDataType="tableDataType"
      @cancel="handleCancel()"
      @ok="handleOk()"
      :customFooter="modalFooter"
    />

    <!-- 查看附件 -->
    <viewFileModal
      :visible.sync="viewFileModal.visible"
      :fileList="viewFileModal.fileList"
      :subtitle="viewFileModal.name"
      :replaceFields="{
        fileName: 'name',
      }"
    ></viewFileModal>
  </div>
</template>

<script>
import { axios } from "@/utils/request";
import ScreenConditions from "@/components/extendCustom/ScreenConditions";
import AssociativeSelectGroup from "@/components/extendCustom/AssociativeSelectGroup";
import {
  pageUserOrganization,
  peopleFilesTemplate,
  importPeopleFiles,
} from "@/api/videoMonitoring";
import { downLoadFileByArraybuffer } from "@/utils/util";
import editForm from "@/pages/form/formPreview/edit.vue";
//附件列表
import viewFileModal from "@/components/extendCustom/view-file-modal";
export default {
  components: {
    ScreenConditions,
    AssociativeSelectGroup,
    editForm,
    viewFileModal,
  },
  data() {
    return {
      condition: {
        //标段
        orgCode: undefined,
        //姓名
        userName: "",
      },
      //列表
      loading: false,
      tableData: [],
      pager: {
        page: 1,
        pageSize: 20,
        total: 0,
      },
      //新增编辑
      visible: false,
      confirmLoading: false,
      url: {
        save: "/form/formDatabase/formSave",
        update: "/form/formDatabase/formUpdate",
      },
      tableDataType: "",
      tableUuid: "4625DAE28B1D43E1BE433EB46D576C82",
      modalFooter: {},
      //查看附件
      viewFileModal: {
        name: "",
        visible: false,
        fileList: [],
      },
      importLoading: false,
      exportLoading: false,
      //标段
      blockLoading: false,
      blockSoucre: [],
    };
  },
  computed: {
    menuName() {
      let { title } = this.$route.meta;
      return title;
    },
  },
  mounted() {
    Promise.all([this.getBlockData(), this.getTableData()]);
  },
  methods: {
    //查询标段
    getBlockData() {
      this.blockLoading = true;
      return new Promise((resolve, reject) => {
        axios
          .get(
            `/probusiness/sysOrg/getAllQxSecsSelect`,
            {},
            {
              headers: {
                "Content-Type": "application/json;charset=UTF-8",
              },
            }
          )
          .then((res) => {
            this.blockSoucre = res ?? [];
            resolve();
          })
          .catch((_) => {
            this.blockSoucre = [];
            reject();
          })
          .finally((_) => {
            this.blockLoading = false;
          });
      });
    },

    //导入
    importTemplate() {
      this.$refs.upload.click();
    },
    importExcel(event) {
      let files = event.target.files;
      let formdata = new FormData();
      for (let i = 0; i < files.length; i++) {
        formdata.append("uploadFile", files[i]);
      }
      this.importLoading = true;
      importPeopleFiles(formdata)
        .then((res) => {
          if (res.statusCode == 200 || res == 1) {
            this.$message.success("导入成功", 1.5);
            this.getTableData();
          } else {
            this.$message.error(res.message);
          }
        })
        .catch((_) => {})
        .finally((_) => {
          event.target.value = "";
          this.importLoading = false;
        });
    },
    //模版下载
    downloadTemplate() {
      peopleFilesTemplate()
        .then((res) => {
          downLoadFileByArraybuffer(res, this.menuName + "模版");
        })
        .catch((_) => {});
    },

    //导出
    exportExcel() {
      this.exportLoading = true;
      let { orgCode = "", userName } = this.condition;
      axios
        .get(
          `/probusiness/zhgdUser/exportExcel?orgCode=${orgCode}&userName=${userName}`,
          {
            apiType: "file",
            responseType: "arraybuffer",
          }
        )
        .then((res) => {
          downLoadFileByArraybuffer(res, this.menuName);
        })
        .catch((_) => {
          this.$message.error("数据导出失败，请稍后重试！");
        })
        .finally((_) => {
          this.exportLoading = false;
        });
    },

    //附件预览
    handelFileModal(row) {
      let fileIdInfo = this.analysisPath(row);
      if (fileIdInfo.length == 0) {
        return;
      }
      this.viewFileModal.name = "附件";
      this.viewFileModal.fileList = fileIdInfo ?? [];
      this.viewFileModal.visible = true;
    },
    analysisPath(row) {
      let {
        photoPath = "[]",
        idCardPath = "[]",
        idCardReversePath = "[]",
      } = row;
      const file_1 = photoPath ? JSON.parse(photoPath) : [];
      const file_2 = idCardPath ? JSON.parse(idCardPath) : [];
      const file_3 = idCardReversePath ? JSON.parse(idCardReversePath) : [];
      let array = [...file_1, ...file_2, ...file_3];
      return array;
    },

    //关闭弹窗
    handleCancel() {
      this.visible = false;
    },
    handleOk() {
      this.visible = false;
      this.getTableData();
    },
    // 新增
    async handleAdd() {
      this.modalFooter = {};
      this.visible = true;
      this.$refs.createModal.title = "新增";
      let formJsonData = await this.loadDataJson(this.tableUuid);
      let { addApiUrl } = JSON.parse(formJsonData)?.config ?? {};
      console.log(addApiUrl, "addApiUrl");

      this.url.save = addApiUrl ?? "/form/formDatabase/formSave";
      this.$refs.createModal.loadData(this.tableUuid, "add", formJsonData);
    },
    //编辑
    async editor(record = {}) {
      this.modalFooter = {};
      let { uuid } = record;
      this.visible = true;
      let formJsonData = await this.loadDataJson(this.tableUuid);
      //   let { editApiUrl } = JSON.parse(formJsonData)?.config ?? {};
      //   this.url.update = editApiUrl ?? "/form/formDatabase/formUpdate";
      this.$refs.createModal.title = "编辑";
      this.$refs.createModal.loading = true;
      this.$post("/form/formDatabase/formGetDetail", {
        uuid: uuid,
        formUuid: this.tableUuid,
      }).then((res) => {
        this.$refs.createModal.loadData(
          this.tableUuid,
          "edit",
          formJsonData,
          res
        );
      });
    },
    //查看
    async gotoDetail(row) {
      this.modalFooter = { footer: null };
      let { uuid } = row;
      this.visible = true;
      let formJsonData = await this.loadDataJson(this.tableUuid);
      this.$refs.createModal.title = "详情";
      this.$refs.createModal.loading = true;
      this.$post("/form/formDatabase/formGetDetail", {
        uuid: uuid,
        formUuid: this.tableUuid,
      }).then((res) => {
        this.$refs.createModal.loadData(
          this.tableUuid,
          "view",
          this.dealData(true, formJsonData),
          res
        );
      });
    },

    loadDataJson(tableUuid = "") {
      return new Promise((reslove) => {
        this.$post("/form/formBasicConfigure/getDetailByUuid", {
          uuid: tableUuid,
        })
          .then((res) => {
            this.tableDataType = res.formDatabase?.type || "";
            reslove(res.formDesign.designJson);
          })
          .catch((_) => {
            reslove({});
          });
      });
    },

    //详情禁用
    dealData(disabled = false, formJsonData = "{}") {
      let dealData = JSON.parse(formJsonData);
      let { list = [], config } = dealData;
      config.hideRequiredMark = true;
      list.forEach((v) => {
        let { columns = [], options } = v;
        if (options) {
          options.disabled = disabled;
        }
        columns.forEach((item) => {
          let { list = [] } = item;
          list.forEach((c) => {
            let { options } = c;
            options.disabled = disabled;
          });
        });
      });
      return JSON.stringify(dealData);
    },

    //删除
    handleDelClick(row) {
      let dataLength = this.tableData.length;
      let that = this;
      that.$confirm({
        title: "提示",
        content: "确定删除该数据吗？删除之后不可恢复！",
        okText: "确定",
        cancelText: "取消",
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          that
            .$post("/form/formDatabase/formDelete", {
              uuid: row.uuid,
              formUuid: that.tableUuid,
            })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                that.$message.success("删除成功", 1.5);
                if (dataLength == 1 && that.pager.page > 1) {
                  that.pager.page -= 1;
                }
                that.getTableData();
              } else {
                that.$message.error(res.message);
              }
            })
            .catch((_) => {});
        },
      });
    },

    search() {
      this.pager.page = 1;
      this.getTableData();
    },
    reset() {
      this.condition.userName = "";
      this.condition.orgCode = undefined;
      this.search();
    },

    getTableData() {
      this.loading = true;
      let { page, pageSize } = this.pager;
      let { orgCode = "", userName } = this.condition;
      pageUserOrganization({
        page,
        pageSize,
        org_code: orgCode,
        userName: userName,
      })
        .then((res) => {
          this.tableData = res?.rows || [];
          this.pager.total = res?.totalCount || 0;
        })
        .catch((_) => {
          this.tableData = [];
          this.pager.total = 0;
        })
        .finally((_) => {
          this.loading = false;
        });
    },
    //监听分页切换
    paginationChange({ currentPage, pageSize }) {
      this.pager.page = currentPage;
      this.pager.pageSize = pageSize;
      this.getTableData();
    },

    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
  },
};
</script>

<style lang="less" scoped></style>
